
package com.mengmeizi;

import com.mengmeizi.interfaces.JsonInflater;
import com.mengmeizi.net.Method;
import com.mengmeizi.services.UpgradeService;
import com.mengmeizi.threads.URLDataThread;
import com.mengmeizi.util.Const;
import com.mengmeizi.util.CustomDialog;
import com.mengmeizi.util.DialogUtil;
import com.mengmeizi.util.FileUtil;
import com.mengmeizi.util.LogOut;
import com.mengmeizi.util.Tools;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.io.File;

public class ActMore extends Activity implements OnClickListener, Callback, JsonInflater {

    private SoftApplication application;

    private String[] names = {
            "自动切换壁纸", "清除图片缓存"
    };

    private String[] names2 = {
            "缓存路径", "检查更新", "提交反馈", "关于我们", "退出"
    };

    private int[] icons = {
            R.drawable.ic_switch_wallpaper, R.drawable.ic_clear_imgcache
    };

    private int[] icons2 = {
            R.drawable.ic_cache_path, R.drawable.ic_update, R.drawable.ic_feedback, R.drawable.ic_about,
            R.drawable.ic_quit
    };

    private LinearLayout layout1, layout2;

    private LayoutInflater inflater;

    private ImageView imvTitle;

    private Handler handler;

    /** 缓存图片占用的空间大小。 */
    private long allFileSize;

    /** 缓存图片的个数。 */
    private int allFileAmount;

    private ScanImageCacheThread thread;

    private ClearImageThread clearImageThread;

    private CustomDialog quitDialog, clearCacheDialog;

    private SharedPreferences preSetting;

    private ImageView imvMoreDesc;

    private String upgradeUrl;

    private CustomDialog upgradeDialog;

    private boolean isShowing;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_more);

        application = (SoftApplication) getApplication();

        application.addActivity(this);

        inflater = getLayoutInflater();

        handler = new Handler(this);

        initMoreView();

    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case Const.DIALOG_SHOW:
                showDialog(Const.DIALOG_ID);
                isShowing = true;
                break;
            case Const.DIALOG_DISMISS:
                if (isShowing) {
                    isShowing = false;
                    dismissDialog(Const.DIALOG_ID);
                }
                break;
            case Const.DIALOG_QUIT_BUTTON:
                // 退出
                DialogUtil.dismissDialog(quitDialog);
                application.exit();
                break;
            case Const.DIALOG_CANCEL_BUTTON:
                if (quitDialog != null) {
                    DialogUtil.dismissDialog(quitDialog);
                }
                if (clearCacheDialog != null) {
                    if (thread != null) {
                        thread.stopRunning();
                    }
                    allFileSize = allFileAmount = 0;
                    DialogUtil.dismissDialog(clearCacheDialog);
                }
                break;
            case Const.DIALOG_CONFIRM_BUTTON:
                if (allFileAmount > 0) {
                    // 确认清除图片缓存
                    clearImageThread = new ClearImageThread();
                    clearImageThread.start();
                    Tools.showShortToast(this, getString(R.string.clearFinish));
                }
                DialogUtil.dismissDialog(clearCacheDialog);
                break;
            case Const.ACT$MORE_CLEARCACHE_UPDATE:
                clearCacheDialog.setContent(getImageCacheSummary());
                break;
            case Const.ACT$MORE_CLEARCACHE_COMPLETE:
                if (allFileAmount > 0 && allFileSize > 0) {
                    clearCacheDialog.setContent(getImageCacheSummary());
                } else {
                    clearCacheDialog.setContent(getString(R.string.noImageCache));
                }
                clearCacheDialog.leftButton().setBackgroundResource(R.xml.btn_dialog_left_selector);
                clearCacheDialog.leftButton().setEnabled(true);
                break;
            case Const.ACT$MORE_UPGRADE:
                handler.sendEmptyMessage(Const.DIALOG_DISMISS);
                upgradeUrl = (String) msg.obj;
                Tools.showNotification(ActMore.this, getString(R.string.upgradeTitle),
                        getString(R.string.upgradeMessage), upgradeUrl);
                upgradeDialog = DialogUtil.showAlertDialog(ActMore.this, handler, getString(R.string.upgradeTitle),
                        getString(R.string.upgradeMessageButton), Const.ACT_CONFIRM, Const.ACT_CANCEL);
                break;
            case Const.ACT_CONFIRM:
                Intent intent = new Intent(this, UpgradeService.class);
                intent.putExtra("downUrl", upgradeUrl);
                ActMore.this.startService(intent);
                DialogUtil.dismissDialog(upgradeDialog);
                break;
            case Const.ACT_CANCEL:
                DialogUtil.dismissDialog(upgradeDialog);
                break;
            case Const.SHOW_TOAST:
                Tools.showShortToast(this, (String) msg.obj);
                handler.sendEmptyMessage(Const.DIALOG_DISMISS);
                break;
            case Const.CHECK_NETWORK:
                handler.sendEmptyMessage(Const.DIALOG_DISMISS);
                Tools.showShortToast(this, getString(R.string.checkNetwork));
                break;
            default:
                break;
        }
        return false;
    }

    private String getImageCacheSummary() {
        // String line = "文件数量：" + allFileAmount + "\n"//
        // + "占用空间：" + Tools.sizeTransB(allFileSize) + "\n";
        String line = "";
        if (allFileSize > 0 && Tools.hasSDCard()) {
            line = getString(R.string.clearCacheMessage, Tools.sizeTransB(allFileSize));
        } else {
            line = getString(R.string.noImageCache);
        }
        return line;
    }

    private void initMoreView() {
        imvTitle = (ImageView) findViewById(R.id.imvTitle);
        imvTitle.setOnClickListener(this);

        layout1 = (LinearLayout) findViewById(R.id.list_layout1);
        layout2 = (LinearLayout) findViewById(R.id.list_layout2);
        initItem(names, icons, layout1);
        initItem(names2, icons2, layout2);

        preSetting = getSharedPreferences(Const.SHARED_PREFERENCES_MESSAGE, Context.MODE_PRIVATE);
        if (preSetting.getBoolean(Const.SHP_MORE, true)) {
            imvMoreDesc = (ImageView) findViewById(R.id.imvMoreDesc);
            imvMoreDesc.setOnClickListener(this);
            imvMoreDesc.setVisibility(View.VISIBLE);
        }
    }

    private void initItem(String[] names, int[] icons, LinearLayout layout) {
        if (names != null && layout != null) {
            for (int i = 0; i < names.length; i++) {
                View listView = inflater.inflate(R.layout.item_more_list_lly, null);
                LinearLayout itemLayout = (LinearLayout) listView.findViewById(R.id.item_layout);
                itemLayout.setTag(names[i]);
                ((TextView) listView.findViewById(R.id.txvItemName)).setText(names[i]);
                ((ImageView) listView.findViewById(R.id.imvItemIcon)).setImageResource(icons[i]);
                if (i == 0) {
                    itemLayout.setBackgroundResource(R.xml.bg_list_up_selector);
                } else if (i == (names.length - 1)) {
                    itemLayout.setBackgroundResource(R.xml.bg_list_down_selector);
                } else {
                    itemLayout.setBackgroundResource(R.xml.bg_list_middle_selector);
                }
                itemLayout.setOnClickListener(item_listener);
                layout.addView(itemLayout);
            }
        }

    }

    private OnClickListener item_listener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            String tag = v.getTag().toString();
            if (names[0].equals(tag)) {
                Tools.switchActivity(ActMore.this, ActSwitchWallpaper.class, null);
                ActMore.this.finish();
            } else if (names[1].equals(tag)) {
                showClearCacheDialog();
            } else if (names2[0].equals(tag)) {
                Tools.switchActivity(ActMore.this, ActImageCache.class, null);
            } else if (names2[1].equals(tag)) {
                // 检查更新
                checkUpgrade();
            } else if (names2[2].equals(tag)) {
                Tools.switchActivity(ActMore.this, ActFeedback.class, null);
            } else if (names2[3].equals(tag)) {
                Tools.switchActivity(ActMore.this, ActAbout.class, null);
            } else if (names2[4].equals(tag)) {
                // 退出
                quitDialog = DialogUtil.showQuitDialog(ActMore.this, handler);
            }
        }

    };

    @Override
    public void onClick(View v) {
        if (v instanceof Button) {
            ;
        } else if (v instanceof ImageView) {
            if (v == imvTitle) {
                this.finish();
            } else if (v == imvMoreDesc) {
                imvMoreDesc.setClickable(false);
                imvMoreDesc.setVisibility(View.GONE);
                Editor editor = preSetting.edit();
                editor.putBoolean(Const.SHP_MORE, false);
                editor.commit();
            }
        }
    }

    /***
     * 检查更新
     */
    protected void checkUpgrade() {
        handler.sendEmptyMessage(Const.DIALOG_SHOW);
        URLDataThread thread = new URLDataThread(this, this, Const.URL_UPGRADE, null, null, Method.GET,
                Const.ACT$MORE_UPGRADE);
        thread.start();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            this.finish();
        }
        return super.onKeyDown(keyCode, event);
    }

    /** 清除图片缓存提示框 */
    private void showClearCacheDialog() {
        allFileSize = allFileAmount = 0;
        clearCacheDialog = DialogUtil.showAlertDialog(this, handler, "", getString(R.string.scanning),
                Const.DIALOG_CONFIRM_BUTTON, Const.DIALOG_CANCEL_BUTTON);
        clearCacheDialog.leftButton().setBackgroundResource(R.drawable.btn_dialog_left_enable);
        clearCacheDialog.leftButton().setEnabled(false);
        // 启动线程
        thread = new ScanImageCacheThread();
        thread.start();
    }

    class ScanImageCacheThread extends Thread {
        private boolean running = true;

        public void stopRunning() {
            running = false;
        }

        @Override
        public void run() {
            File cacheFolder = new File(Const.FILENAME_IMGCACHE);
            if (cacheFolder.exists() && cacheFolder.isDirectory()) {
                File[] arr = cacheFolder.listFiles();
                if (arr != null && arr.length > 0) {
                    for (int i = 0; i < arr.length && running; i++) {
                        File tmp = arr[i];
                        allFileAmount++;
                        allFileSize += tmp.length();
                        // 每遍历50个就刷新一次界面。
                        if (i % 50 == 0) {
                            handler.sendEmptyMessage(Const.ACT$MORE_CLEARCACHE_UPDATE);
                        }
                    }
                }
                handler.sendEmptyMessage(Const.ACT$MORE_CLEARCACHE_COMPLETE);
            }
        }
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        ProgressDialog dialog = new ProgressDialog(this);
        // dialog.setIndeterminateDrawable(getResources().getDrawable(R.anim.refresh_round));
        dialog.setMessage(getString(R.string.loading));
        dialog.setIndeterminate(false);
        return dialog;
    }

    class ClearImageThread extends Thread {

        @Override
        public void run() {
            try {
                FileUtil.mkdir(Const.FILENAME_IMGCACHE, true);
            } catch (Exception e) {
                e.printStackTrace();
            }
            super.run();
        }

    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    public void inflateByJson(int type, String jsonStr, int what) {
        LogOut.out(this, "jsonData[" + jsonStr + "]");
        JSONObject object = null;
        Message msg = null;
        try {
            if (type == JsonInflater.TYPE_OK && jsonStr != null) {
                object = new JSONObject(jsonStr);
                String status = object.getString("status");
                object = object.getJSONObject("result");
                if (what == Const.ACT$MORE_UPGRADE) {
                    if (status.equals("success")) {
                        // 获取的versioncode
                        int remoteVersionCode = object.getInt("versionCode");
                        // 编译的versioncode
                        PackageInfo pinfo = getPackageManager().getPackageInfo(getPackageName(), 0);
                        int buildVersionCode = pinfo.versionCode;
                        if (remoteVersionCode > buildVersionCode) {
                            msg = handler.obtainMessage();
                            msg.what = Const.ACT$MORE_UPGRADE;
                            msg.obj = object.getString("url");
                            handler.sendMessage(msg);
                        } else {
                            msg = handler.obtainMessage();
                            msg.obj = getString(R.string.newVersion);
                            msg.what = Const.SHOW_TOAST;
                            handler.sendMessage(msg);
                        }
                    }
                }
            } else if (type == JsonInflater.TYPE_SERVER_ERROR) {
                // handler.sendEmptyMessage(Const.DIALOG_DISMISS);
                msg = handler.obtainMessage();
                msg.obj = getString(R.string.serverError);
                msg.what = Const.SHOW_TOAST;
                handler.sendMessage(msg);
            }else if(type == JsonInflater.TYPE_NETWORK_ERROR){
                handler.sendEmptyMessage(Const.CHECK_NETWORK);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        isShowing = false;
    }

    // protected void checkUpgradeTest() {
    // try {
    // JSONObject object = new JSONObject(Tools.loadHttpData(this, "upgrade"));
    // String status = object.getString("status");
    // object = object.getJSONObject("result");
    // if (status.equals("success")) {
    // // 获取的versioncode
    // int remoteVersionCode = object.getInt("versionCode");
    // // 编译的versioncode
    // PackageInfo pinfo = getPackageManager().getPackageInfo(getPackageName(),
    // 0);
    // int buildVersionCode = pinfo.versionCode;
    // if (remoteVersionCode > buildVersionCode) {
    // Message msg = handler.obtainMessage();
    // msg.what = Const.ACT$MORE_UPGRADE;
    // msg.obj = object.getString("url");
    // handler.sendMessage(msg);
    // }
    // }
    // } catch (Exception e) {
    // e.printStackTrace();
    // }
    // }

}
